import json
from django.http import JsonResponse
from django.utils.decorators import method_decorator

from user.models import Role, Permission
from django.views import View
from django_system.role_recognize import check_permission


class ChangePermissions(View):

    @method_decorator(check_permission(['管理员']))
    def post(self, request, r_id):
        permissions = json.loads(request.body).get('permissions')
        role = Role.objects.get(id=r_id)
        for i in permissions:
            permission = Permission.objects.get(title=i)
            role.permissions.add(permission)
        return JsonResponse({'status': 'ok', 'code': 200, 'msg': '添加权限成功'})

    @method_decorator(check_permission(['管理员']))
    def delete(self, request, r_id):
        permissions = json.loads(request.body).get('permissions')
        role = Role.objects.get(id=r_id)
        for i in permissions:
            permission = Permission.objects.get(title=i)
            role.permissions.remove(permission)
        return JsonResponse({'status': 'ok', 'code': 200, 'msg': '删除权限成功'})


class AddPermissions(View):
    @method_decorator(check_permission(['管理员']))
    def post(self, request):
        data = json.loads(request.body)
        url = data['url']
        title = data['title']
        try:
            Permission.objects.create(url=url, title=title)
            return JsonResponse({'status': 'ok', 'code': 200, 'msg': '添加权限成功'})
        except Exception as e:
            return JsonResponse({'status': 'fail', 'code': 200, 'msg': '添加失败原因是%s' % e})

    @method_decorator(check_permission(['管理员']))
    def put(self, request, id):
        data = json.loads(request.body)
        url = data['url']
        title = data['title']
        try:
            Permission.objects.filter(id=id).update(url=url, title=title)
            return JsonResponse({'status': 'ok', 'code': 200, 'msg': '修改权限成功'})
        except Exception as e:
            return JsonResponse({'status': 'fail', 'code': 400, 'msg': '修改失败原因是%s' % e})

    @method_decorator(check_permission(['管理员']))
    def delete(self, request, id):
        try:
            Permission.objects.get(id=id).update(is_delete=True)
            return JsonResponse({'status': 'ok', 'code': 200, 'msg': '删除权限成功'})
        except Exception as e:
            return JsonResponse({'status': 'fail', 'code': 200, 'msg': '删除失败原因是%s' % e})
